<template>
  <div>
    <div>
      <!-- Tab列表 -->
      <nav class="bignav">
        <div class="nav">
          <span
            :class="`${active === 'redian' ? 'active' : ''}`"
            @click="TabClick('redian')"
            >热点</span
          >
          <span
            :class="`${active === 'yule' ? 'active' : ''}`"
            @click="TabClick('yule')"
            >娱乐</span
          >
          <span
            :class="`${active === 'jiankang' ? 'active' : ''}`"
            @click="TabClick('jiankang')"
            >健康</span
          >
          <span
            :class="`${active === 'shehui' ? 'active' : ''}`"
            @click="TabClick('shehui')"
            >社会</span
          >
          <span
            :class="`${active === 'lvyou' ? 'active' : ''}`"
            @click="TabClick('lvyou')"
            >旅游</span
          >
          <span
            :class="`${active === 'tiyu' ? 'active' : ''}`"
            @click="TabClick('tiyu')"
            >体育</span
          >
          <span
            :class="`${active === 'caijing' ? 'active' : ''}`"
            @click="TabClick('caijing')"
            >财经</span
          >
          <span
            :class="`${active === 'qiche' ? 'active' : ''}`"
            @click="TabClick('qiche')"
            >汽车</span
          >
          <span
            :class="`${active === 'youxi' ? 'active' : ''}`"
            @click="TabClick('youxi')"
            >游戏</span
          >
          <span
            :class="`${active === 'keji' ? 'active' : ''}`"
            @click="TabClick('keji')"
            >科技</span
          >
          <span
            :class="`${active === 'junshi' ? 'active' : ''}`"
            @click="TabClick('junshi')"
            >军事</span
          >
          <span
            :class="`${active === 'lishi' ? 'active' : ''}`"
            @click="TabClick('lishi')"
            >历史</span
          >
        </div>
      </nav>
      <van-pull-refresh
        v-model="isLoading"
        @refresh="onRefresh"
        :pulling-text="''"
        :loosing-text="'释放刷新...'"
      >
        <div class="loadingDiv" v-if="!newsDataList.length">
          <van-loading />
        </div>
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          v-else
        >
          <div
            class="content"
            v-for="(item, index) in newsDataList"
            :key="index"
            @click="RouterHandle(item)"
          >
            <div class="news-item">
              <div class="left">
                <div class="left-Title">{{ item.title }}</div>
                <div class="source">
                  <div>{{ item.source }}</div>
                  <div
                    class="close"
                    style="cursor: pointer"
                    @click.stop="clonsHandle(item)"
                  >
                    <van-icon name="cross" />
                  </div>
                </div>
              </div>
              <img class="img" :src="item.pic" alt />
            </div>
          </div>
        </van-list>
      </van-pull-refresh>

      <div class="closePopup">
        <van-popup v-model="show">
          <div @click="NoInterest">
            <van-icon name="close" />
            <span class="closePopupItem">不感兴趣</span>
          </div>
          <div class="closePopupItem-bottom">
            <!-- <van-icon name="warning-o" />
          <span class="closePopupItem">
              <span>举报内容</span>
              <div class="detail-bottom">内容质量差 标题党 低俗 暴力血腥 恶心</div>
            </span>-->
            <div
              style="
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <van-icon name="warning-o" />
            </div>
            <div class="report" @click="reportShow = true">
              <span>举报内容</span>
              <span style="color: #999999; font-size: 10px; margin-top: 3px"
                >内容质量差 标题党 低俗 暴力血腥 恶心</span
              >
            </div>
          </div>
        </van-popup>
      </div>
    </div>
    <!-- 网络错误 -->
    <!-- <div class="networkError" v-show="!networkErrorShow">
      <div class="title">
        <van-icon name="arrow-left" @click="GobackList"/>
      </div>
      <div class="content" >
        <img :src="require('../assets/retry2.png')" alt  />
        <div class="hintText">网络不给力，获取数据失败~</div>
        <div >
          <van-button round  @click="GobackList">重新加载</van-button>
        </div>
      </div>
    </div> -->
    <!-- 举报选项 -->
    <div class="NoInterestClass">
      <van-action-sheet
        v-model="reportShow"
        title="举报文章问题"
        :close-on-click-overlay="false"
        @close="closereportShow"
      >
        <van-radio-group v-model="radio">
          <!-- <van-checkbox-group v-model="checkboxGroup" direction="horizontal"> -->
          <!-- <van-cell-group> -->
          <van-cell title="涉政反动" clickable @click="radio = '涉政反动'">
            <template #right-icon>
              <!-- <van-checkbox  name="涉政反动"></van-checkbox> -->
              <van-radio name="涉政反动" />
            </template>
          </van-cell>
          <van-cell title="色情低俗" clickable @click="radio = '色情低俗'">
            <template #right-icon>
              <van-radio name="色情低俗" />
            </template>
          </van-cell>
          <van-cell title="血腥暴力" clickable @click="radio = '血腥暴力'">
            <template #right-icon>
              <van-radio name="血腥暴力" />
            </template>
          </van-cell>
          <van-cell
            title="涉嫌违法犯罪"
            clickable
            @click="radio = '涉嫌违法犯罪'"
          >
            <template #right-icon>
              <van-radio name="涉嫌违法犯罪" />
            </template>
          </van-cell>
          <van-cell title="赌博、诈骗" clickable @click="radio = '赌博、诈骗'">
            <template #right-icon>
              <van-radio name="赌博、诈骗" />
            </template>
          </van-cell>
          <van-cell
            title="内容不实、谣言"
            clickable
            @click="radio = '内容不实、谣言'"
          >
            <template #right-icon>
              <van-radio name="内容不实、谣言" />
            </template>
          </van-cell>
          <van-cell
            title="侵权（抄袭、侵犯名誉等)"
            clickable
            @click="radio = '侵权（抄袭、侵犯名誉等)'"
          >
            <template #right-icon>
              <van-radio name="侵权（抄袭、侵犯名誉等)" />
            </template>
          </van-cell>
          <van-cell
            title="疑似侵犯未成年人权益"
            clickable
            @click="radio = '疑似侵犯未成年人权益'"
          >
            <template #right-icon>
              <van-radio name="疑似侵犯未成年人权益" />
            </template>
          </van-cell>
          <van-cell
            title="已过时效旧闻"
            clickable
            @click="radio = '已过时效旧闻'"
          >
            <template #right-icon>
              <van-radio name="已过时效旧闻" />
            </template>
          </van-cell>
          <van-cell
            title="其他问题，我要吐槽"
            clickable
            @click="commentShowhandle"
          >
            <!-- @click="commentShow = true" -->
            <div>
              <van-icon name="arrow" />
            </div>
          </van-cell>
          <!-- </van-cell-group> -->
          <!-- </van-checkbox-group> -->
        </van-radio-group>
        <div
          style="display: flex; justify-content: center; align-items: center"
        >
          <van-button
            round
            type="primary"
            style="
              width: 327px;
              height: 40px;
              margin: 12px auto;
              background-color: #38cdd8;
              border: 0;
              color: #fff;
            "
            @click="reported"
            >完成</van-button
          >
        </div>
      </van-action-sheet>
    </div>
    <!-- 我要吐槽 -->
    <div class="comment">
      <van-action-sheet
        v-model="commentShow"
        title="我要吐槽"
        :close-on-click-overlay="false"
        @close="closecommentShow"
      >
        <van-field
          ref="Input"
          v-model="commentValue"
          autosize
          type="textarea"
          placeholder="请具体说明问题，我们将尽快处理"
        />
        <div
          style="display: flex; justify-content: center; align-items: center"
        >
          <van-button
            round
            type="primary"
            style="
              width: 327px;
              height: 40px;
              margin: 30px auto;
              background-color: #38cdd8;
              border: 0;
              color: #fff;
            "
            @click="reported"
            >完成</van-button
          >
        </div>
        <div id="autoHeightID" class="autoHeight" style="width: 100%;height: 400px;"></div>
      </van-action-sheet>
    </div>
  </div>
</template>

<script>
import { getCategoryAPI } from "../apis/category";
import { getPostAPI } from "../apis/news";
import { getToken } from "../utils/localData";
import axios from "axios";

export default {
  name: "home",
  components: {},
  data() {
    return {
      active: "",
      newsDataList: [],
      loading: false,
      finished: false,
      page: 0,
      show: false,
      networkErrorShow: true,
      reportShow: false,
      radio: "涉政反动",
      commentShow: false,
      commentValue: "",
      isLoading: false,
      appkey: "",
      beginTimestamp: "",
      // endTimestamp: '',
      // 二级tab切换埋点上报字段
      firsttabname: "资讯", // 所一级Tab
      secondarytabname: "热门", //二级Tab名称
      Time: "", //二级Tab浏览时长
      ArticleReadcnt: "", //文章阅读数量
      urid: "", //用户名
      user: "", //用户名
      // tabName: JSON.parse(localStorage.getItem('tabName')) || '',
      articlesNumber: 0,
      // 文章举报埋点
      Position: "列表页",
      Tite: "",
      Url: "",
      Msg: "",
      isAndroid: false,
      isiOS: false,
      detailPagetab: '', // 进入二级tab给 原生传当前tab 用于详情页
    };
  },
  mounted() {
    this.beginTimestamp = Math.floor(Date.now() / 1000);  // H5第一次加载 记录时间
    this.isAndroidOriosFn();
    // 一级tab切换 进入
    window["onVisibleToUser"] = () => {
      try{
        this.beginTimestamp = Math.floor(Date.now() / 1000)
      }catch(err){
        this.beginTimestamp = Math.floor(Date.now() / 1000)
      }
    };
    // 一级tab切换 离开
    window["onInvisibleToUser"] = () => {
    this.Tabswitchover()
    };
  },
  computed: {
    getSecondarytabname() {
      let Name = "";
      if (this.active === "redian") Name = "热点";
      if (this.active === "yule") Name = "娱乐";
      if (this.active === "jiankang") Name = "健康";
      if (this.active === "shehui") Name = "社会";
      if (this.active === "lvyou") Name = "旅游";
      if (this.active === "tiyu") Name = "体育";
      if (this.active === "caijing") Name = "财经";
      if (this.active === "qiche") Name = "汽车";
      if (this.active === "youxi") Name = "游戏";
      if (this.active === "keji") Name = "科技";
      if (this.active === "junshi") Name = "军事";
      if (this.active === "lishi") Name = "历史";
      return Name;
    },
    getdetailname() {
      let Name = "";
      if (this.detailPagetab === "redian") Name = "热点";
      if (this.detailPagetab === "yule") Name = "娱乐";
      if (this.detailPagetab === "jiankang") Name = "健康";
      if (this.detailPagetab === "shehui") Name = "社会";
      if (this.detailPagetab === "lvyou") Name = "旅游";
      if (this.detailPagetab === "tiyu") Name = "体育";
      if (this.detailPagetab === "caijing") Name = "财经";
      if (this.detailPagetab === "qiche") Name = "汽车";
      if (this.detailPagetab === "youxi") Name = "游戏";
      if (this.detailPagetab === "keji") Name = "科技";
      if (this.detailPagetab === "junshi") Name = "军事";
      if (this.detailPagetab === "lishi") Name = "历史";
      return Name;
    },
  },
  created() {
    this.TabClick("redian");
    this.androidorios();
  },
  methods: {
    TabClick(T) {
      // console.log(T == this.active);
      if(T == this.active) return
     this.detailPagetab = T  // 给详情页的
      this.Tabswitchover();  // 在切换二级tab之前 上报
      this.active = T;
      this.newsDataList = [];
      this.page = 0;
      axios
        .get(
          `https://api.fkcaijing.com/202308/59.php?column=${this.active}&page=${this.page}`
        )
        .then((res) => {
          this.newsDataList = res.data.list;
        })
        .catch((err) => {
          this.networkErrorShow = false;
        });
      this.articlesNumber = 0; // 确保切换tab都是文章数量为0
     
    },
    //切换tab埋点上报
    Tabswitchover() {
      this.isAndroidOriosFn();
      this.Time = Math.floor(Date.now() / 1000) - this.beginTimestamp; // 浏览时间
      this.beginTimestamp = Math.floor(Date.now() / 1000); // 时间戳重置
      this.secondarytabname = this.getSecondarytabname;
      let infoData = {
        firsttabname: "资讯",
        secondarytabname: this.secondarytabname,
        Time: this.Time,
        ArticleReadcnt: this.articlesNumber,
      };
      const StyObj = JSON.stringify(infoData);
      console.log(infoData,'infoData');
      if (this.isAndroid) {
        try{
          androidNative.uploadAnsLog("ViewSecondLevelTab", StyObj);
        }catch(err){}
      } else if (this.isiOS) {
        let iosobj = {
          MoudleName: "ViewSecondLevelTab",
          firsttabname: "资讯",
          secondarytabname: this.secondarytabname,
          Time: this.Time,
          ArticleReadcnt: this.articlesNumber,
        };
        console.log(iosobj,'iosobj');
        window.webkit.messageHandlers.uploadAnsLog.postMessage(iosobj);
      }
    },
  

    // 上拉加载分页
    onLoad() {
      this.page += 1;
      //  this.loading = true
      axios
        .get(
          `https://api.fkcaijing.com/202308/59.php?column=${this.active}&page=${this.page}`
        )
        .then((res) => {
          this.loading = false; // 加载状态结束
          this.newsDataList.push(...res.data.list);

          if (res.data.list < 10) {
            this.finished = true; // 数据全部加载完成
          }
        })
        .catch((err) => {
          this.networkErrorShow = false;
        });
    },
    RouterHandle(item) {
      console.log(item);
      this.Tite = item.title;
      this.Url = item.url;
      this.articlesNumber = 1;
      try {
        this.Tabswitchover();
        window.location.href = item.url;
      } catch (err) {
        window.location.href = item.url;
      }
    },
    isAndroidOriosFn() {
      console.log(this.getdetailname,'getdetailname');
      if (this.isAndroid) {
        try{
          window.webkit.onShowSecondTabName(this.getdetailname);
        }catch(err){

        }
      } else if (this.isiOS) {
        window.webkit.messageHandlers.onShowSecondTabName.postMessage(
          this.getdetailname
        );
      }
    },
    closereportShow() {
      this.radio = "涉政反动";
    },
    // 举报完成提交
    reported() {
      if(this.radio == '' && this.commentValue == '' && !this.commentShow) {
        this.$toast('请选择选项')
        return
      }
      //打开吐槽不输入 不给点完成
      if(this.commentShow && this.commentValue == '') {
        this.$toast('请输入内容')
        return
      } 
      this.secondarytabname = this.getSecondarytabname;
      let obj = {
        Click: "举报",
        Firsttabname: "资讯",
        secondarytabname: this.secondarytabname,
        Position: "列表",
        Title: this.Tite,
        Url: this.Url,
        Msg: [this.radio],
        MsgContent: this.commentValue,
      };
      console.log(obj);
      let StyObj = JSON.stringify(obj);
      try {
        if (this.isAndroid) {
          androidNative.uploadAnsLog("Tipoff", StyObj);
        } else if (this.isiOS) {
          let iosobj = {
            MoudleName: "Tipoff",
            Click: "举报",
            Firsttabname: "资讯",
            secondarytabname: this.secondarytabname,
            Position: "列表",
            Title: this.Tite,
            Url: this.Url,
            Msg: [this.radio],
            MsgContent: this.commentValue,
          };
          window.webkit.messageHandlers.uploadAnsLog.postMessage(iosobj);
        }
      } catch (err) {
        this.reportedCallback();
      }
      this.reportedCallback();
    },
    reportedCallback() {
      this.show = false;
      this.reportShow = false;
      this.commentShow = false;
      this.commentValue = "";
      this.$toast("举报成功");
    },

    // 关闭 清空吐槽内容
    closecommentShow() {
      this.commentValue = "";
    },
    // 点击 ×
    clonsHandle(item) {
      this.show = true;
      this.Tite = item.title;
      this.Url = item.url;
    },
    // 不感兴趣
    NoInterest() {
      let obj = {
        Click: "不感兴趣",
        Firsttabname: "资讯",
        secondarytabname: this.getSecondarytabname,
        Position: "列表",
        Title: this.Tite,
        Url: this.Url,
         Msg: [''],
        MsgContent: '',
      };
      console.log(obj);
      let StyObj = JSON.stringify(obj);
      try {
        if (this.isAndroid) {
          androidNative.uploadAnsLog("Tipoff", StyObj);
        } else if (this.isiOS) {
          let iosobj = {
            MoudleName: "Tipoff",
            Click: "不感兴趣",
            Firsttabname: "资讯",
            secondarytabname: this.getSecondarytabname,
            Position: "列表",
            Title: this.Tite,
            Url: this.Url,
            Msg: [''],
            MsgContent: '',

          };
          window.webkit.messageHandlers.uploadAnsLog.postMessage(iosobj);
        }
      } catch (err) {
        this.$toast.success("感谢您的反馈");
        this.show = false;
      }
      this.$toast.success("感谢您的反馈");
      this.show = false;
    },
    
    // 下拉刷新
    onRefresh() {
      this.TabClick(this.active);
      this.isLoading = false;
    },
    // 判断ios 和安卓环境
    androidorios() {
      var u = navigator.userAgent,
        app = navigator.appVersion;
      this.isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //如果输出结果是true就判定是android终端或者uc浏览器
      this.isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //根据输出结果true或者false来判断ios终端
      //!!双叹号一般用来将后面的表达式转换为布尔型的数据（boolean）
    },
    onFocus() {
      if (this.isAndroid) {
        // 安卓弹起有动画 所以加延迟
        setTimeout(() => {
          this.$refs.Input.scrollIntoView(false);
        }, 300);
      } else if (this.isiOS) {
        setTimeout(() => {
          document.body.scrollTop = document.body.scrollHeight;
        }, 300);
      }
    },
    // 我要吐槽
    commentShowhandle(){
      this.commentShow = true
      this.radio = ''
    }
  },
  beforeDestroy() {
    // this.Tabswitchover();
  },
};
</script>

<style lang="less" scoped>
/deep/ .closePopup {
  .van-popup {
    display: flex;
    flex-direction: column;
    justify-content: center;
    justify-content: space-around;
    padding: 16px;
    width: 300px;
    height: 146px;
    background: #ffffff;
    border-radius: 15px;

    .van-icon {
      font-size: 20px;
      // line-height: 50px;
      vertical-align: bottom;
      margin-right: 10px;
    }

    .closePopupItem-bottom {
      display: flex;

      .report {
        display: flex;
        flex-direction: column;
      }
    }
  }
}

.active {
  color: #38cdd8 !important;
  font-weight: 900;
  font-weight: bold;
}

.bignav {
  // position: relative;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  // padding: 0 auto;
  width: 100%;
  width: calc(100vw - 30px);
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;

  .nav {
    display: flex;
    display: -webkit-box;
    overflow-x: scroll;
    box-sizing: border-box;
    // height: 48px;
    background-color: #ffffff;
    font-size: 12px;
    span {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 48px;
      height: 25px;
      // padding: 10px 10px;
      border-radius: 16px;
      margin: 10px 10px 10px 0;
      background: #f8f8f8;
      color: #8d8d8d;
      white-space: nowrap;
    }
  }
}

.loadingDiv {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 26vh !important;
}

/deep/.van-pull-refresh__head {
}

.van-list {
  padding-top: 48px;

  .content {
    margin: 0 15px;

    .news-item {
      display: flex;
      justify-content: space-between;
      padding: 9px 0;
      font-size: 14px;
      border-bottom: 1px solid #ebebeb;

      .left {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .left-Title {
          width: 215px;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 3;
        }

        .source {
          display: flex;
          justify-content: space-between;
          // margin-top: 20px;
          font-size: 10px;
          color: #aaaaaa;

          .close {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 18px;
            height: 12px;
            margin-right: 6px;
            background: #f8f8f8 !important;
            border-radius: 4px;

            /deep/ .van-icon {
              font-size: 8px !important;
              width: 8px;
              height: 8px;
            }
          }
        }
      }

      .img {
        width: 113px;
        height: 72px;
        background: #ccc;
        border-radius: 8px;
      }
    }
  }
}

/deep/ .networkError {
  height: 100vh !important;

  // display: flex;
  // flex-direction: column;
  .title {
    display: flex;
    align-items: center;
    height: 48px;
    padding-left: 14px;

    .van-icon {
      font-size: 26px;
    }
  }

  .content {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 100%;
    height: calc(100vh - 48px) !important;
    margin-top: -48px;

    .hintText {
      font-size: 13px;
      color: #333333;
      line-height: 23px;
      margin: 20px 0;
    }
  }

  // 自动撑高盒
  .autoHeight {
    width: 100%;
    height: 400px;
  }

  .van-button {
    width: 100px;
    height: 31px;
    background-color: #38cdd8;
    border: 1px solid #38cdd8;

    .van-button__text {
      color: #ffffff !important;
      font-size: 15px;
    }
  }
}

/deep/ .NoInterestClass {
  .van-radio__icon--round {
    .van-icon {
      width: 18px;
      height: 18px;
      font-size: 15px;
    }
  }

  .van-radio__icon--checked .van-icon {
    background-color: #38cdd8 !important;
    border: 0;
  }

  .van-cell::after {
    border-bottom: 0;
  }
}
</style>
